package com.yixin.exception;

import com.yixin.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器发生异常：{}", e.getMessage());
        return Result.error("服务器出错，请联系管理员~");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("服务器发生异常：{}", e.getMessage());
        String message = e.getMessage();
        int index = message.indexOf("Duplicate entry");
        if (index != -1) {
            message = message.substring(index + 16, message.indexOf("for key"));
            return Result.error(message + "已存在");
        }
        return Result.error("服务器出错，请联系管理员~");
    }
}
